<template>
  <div class="wrapper-list">
    <!-- 条件区 -->
    <el-row :gutter="10" class="wrapper-condition"></el-row>

    <!-- 列表区 -->
    <div class="wrapper-table">
      <el-table
        v-loading="flagLoading"
        :data="tblDataList"
        :header-cell-style="{ 'text-align': 'center' }"
        row-key="id"
        fit
        highlight-current-row
        style="width: 100%"
      >

        <el-table-column label="标题">
          <template #default="scope">
            <el-link @click="showTask(scope.row.id)">
              {{ scope.row.article.title }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="任务类别" align="center" width="120" prop="categoryName" />

        <el-table-column label="任务级别" align="center" width="100" prop="level" />

        <el-table-column width="120" align="center" label="任务起止时间">
          <template #default="scope">
            <span>
              {{ formatDT(scope.row.dtStart) }}
              <br />至<br />
              {{ formatDT(scope.row.dtEnd) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column width="300" label="责任相关">
          <template #default="scope">
            <el-text type="primary">责任领导：</el-text>{{ scope.row.leaderName }}<br />
            <el-text type="success">责任科室：</el-text>{{ scope.row.departmentName }}<br />
            <el-text type="danger">责任分工：</el-text>{{ scope.row.staffName }}
          </template>
        </el-table-column>

        <el-table-column label="发布时间" align="center" width="120" prop="article.dtCreate" />

        <el-table-column align="center" width="90" label="是否启用">
          <template #default="scope">
            <el-switch
              v-model="scope.row.flagEnabled"
              active-color="#5B7BFA"
              inactive-color="#dadde5"
              @change="onEnabled(scope.row.id)"
            />
          </template>
        </el-table-column>

        <el-table-column align="center" width="90" label="是否完成">
          <template #default="scope">
            <el-switch
              v-model="scope.row.flagFinished"
              active-color="#5B7BFA"
              inactive-color="#dadde5"
              @change="onFinished(scope.row.id)"
            />
          </template>
        </el-table-column>

        <el-table-column width="120" align="center" label="操作">
          <template #default="scope">
            <div class="wrapper-op">
              <a class="ibtn ibtn-green-dark" title="添加子任务" @click="onAddSubTask(scope.row)">
                <el-icon><Plus /></el-icon>
              </a>
              <a class="ibtn ibtn-blue-dark" title="责任管理" @click="onDuty(scope.row)">
                <el-icon><UserFilled /></el-icon>
              </a>
              <a class="ibtn ibtn-blue" title="附件管理" @click="onListFile(scope.row)">
                <el-icon><Paperclip /></el-icon>
              </a>
              <a class="ibtn ibtn-green" title="修改任务" @click="onEdit(scope.row.id)">
                <el-icon><Edit /></el-icon>
              </a>
              <a class="ibtn ibtn-red" title="删除任务" @click="onDelete(scope.row.id)">
                <el-icon><Delete /></el-icon>
              </a>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区 -->
    <div class="wrapper-pager">
      <el-pagination
        :current-page="pageCurrent"
        :page-sizes="pageSizeArrray"
        :page-size="pageSize"
        :total="recordCount"
        :page-count="pageCount"
        background
        small
        layout="prev, pager, next, jumper, sizes"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
    </div>

    <!-- 显示任务内容 -->
    <el-dialog v-model="flagDialogShow" title="任务详情" width="60%" :close-on-click-modal="false">
      <div class="wrapper-article">
        <h4>{{ task.article.title }}</h4>
        <p class="info">发布时间：{{ task.dtCreate }}</p>
        <div v-html="task.article.content"></div>
      </div>
      <template #footer>
        <el-button type="primary" @click="flagDialogShow = false">关 闭</el-button>
      </template>
    </el-dialog>

    <!-- 显示任务附件 -->
    <el-dialog v-model="flagDialogFile" title="任务附件" width="60%" :close-on-click-modal="false">
      <TheUploader :adminId="idAdmin" :taskId="idTask" @setUploadResult="getUploadResult($event)" />
      <div class="wrapper-table">
        <el-table
          v-loading="flagLoading"
          :data="tblFileList"
          :header-cell-style="{ 'text-align': 'center' }"
          row-key="id"
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="编号" type="index" width="60" />

          <el-table-column label="文件名" prop="fileNameShow" />

          <el-table-column label="上传时间" width="200" prop="dtUpload" />

          <el-table-column width="120" align="center" label="操作">
            <template #default="scope">
              <div class="wrapper-op">
                <a title="下载" class="ibtn ibtn-download" @click="onDownload(scope.row.uuid)">
                  <el-icon><Download /></el-icon>
                </a>
                <a class="ibtn ibtn-red" title="删除" @click="onDeleteFile(scope.row.uuid)">
                  <el-icon><Delete /></el-icon>
                </a>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button type="primary" @click="flagDialogFile = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { L } from '@/utils/common'
import { getAdminId } from '@/utils/common'
import { toastSuccess } from '@/utils/toast'
import { setSStorageObj, getLStorageObj } from '@/utils/web-storage'
import { AryToTree } from '@/utils/array'
import { str2Str } from '@/utils/datetime'
import { resolveBlob } from '@/utils/file'

import { ElMessageBox } from 'element-plus'

import TheUploader from '@c/UploadFile2Local'

import router from '@/router'
import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'TaskListPageView',
  components: { TheUploader },
  setup() {
    const idAdmin = ref(0)
    const idCategory = ref(2)
    const treeSelectData = ref([])
    const tblDataList = ref([])
    const tblFileList = ref([])
    const flagLoading = ref(true)

    const pageCurrent = ref(1)
    const pageSize = ref(20)
    const pageSizeArrray = ref([10, 20, 30, 40])
    const recordCount = ref(0)
    const pageCount = ref(1)
    // 对话框
    const flagDialogShow = ref(false)
    const flagDialogFile = ref(false)
    const task = ref({})
    const idTask = ref(0)

    const getIdAdmin = () => {
      idAdmin.value = getAdminId()
    }
    const formatDT = (dtString) => {
      if (!dtString) return
      return str2Str(dtString, 'yyyy-MM-dd HH:mm:ss', '{y}-{m}-{d}')
    }

    // 得到所有任务分类
    const listCategory = () => {
      treeSelectData.value = AryToTree(getLStorageObj('AllCategory'), 2)
    }
    // 从api获取所有管理员列表
    const listAllAdmin = () => {
      store
        .dispatch('sys_admin/listAll', 'task')
        .then((response) => {
          console.log('allAdmin:', response)
        })
        .catch((error) => {
          console.log('读取管理员列表数据出现错误：', error)
        })
    }
    // 列出任务列表
    const listPage = () => {
      flagLoading.value = true
      const paramsJson = {
        PageCurrent: pageCurrent.value,
        PageSize: pageSize.value,
      }
      store
        .dispatch('task/listPage', paramsJson)
        .then((response) => {
          flagLoading.value = false
          tblDataList.value = AryToTree(response.ListData, 0)
          recordCount.value = Number(response.RecordCount)
          pageCount.value = response.PageCount
        })
        .catch(() => {
          flagLoading.value = false
        })
    }
    // 点击每页记录数大小下拉菜单
    const onSizeChange = (val) => {
      pageSize.value = val
      listPage()
    }
    // 点击分页页码
    const onCurrentChange = (val) => {
      pageCurrent.value = val
      listPage()
    }
    // 设置启用状态
    const onEnabled = (idTask) => {
      store
        .dispatch('task/patchStatus', {
          TaskId: idTask,
          Type: 'enabled',
          Status: '',
        })
        .then(() => {
          toastSuccess('设置启用状态成功！')
          listPage()
        })
        .catch((error) => {
          console.log('设置启用状态出现错误：', error)
        })
    }
    // 设置完成状态
    const onFinished = (idTask) => {
      store
        .dispatch('task/patchStatus', {
          TaskId: idTask,
          Type: 'finished',
          Status: '',
        })
        .then(() => {
          toastSuccess('设置完成状态成功！')
          listPage()
        })
        .catch((error) => {
          console.log('设置完成状态出现错误：', error)
        })
    }
    // 设置状态
    const onStatus = (idTask, status) => {
      store
        .dispatch('task/patchStatus', {
          TaskId: idTask,
          Type: 'status',
          Status: status,
        })
        .then(() => {
          toastSuccess('设置任务状态成功！')
          listPage()
        })
        .catch((error) => {
          console.log('设置任务状态出现错误：', error)
        })
    }
    // 添加子任务
    const onAddSubTask = (row) => {
      setSStorageObj('ParamData', row)
      router.push({ path: 'add' })
      // router.push({ name: 'add', params: { id: id } })
    }
    // 跳转到任务责任页
    const onDuty = (row) => {
      setSStorageObj('ParamData', row)
      router.push({ path: 'list-all-duty' })
    }
    // 附件管理
    const onListFile = (row) => {
      idTask.value = row.id
      flagDialogFile.value = true
      listFile()
    }
    // 得到某任务所有附件列表
    const listFile = () => {
      store
        .dispatch('sys_ul_file/listAllByIdTask', idTask.value)
        .then((response) => {
          tblFileList.value = response
        })
        .catch((error) => {
          console.log('得到任务所有附件出现错误：', error)
        })
    }
    // 编辑任务
    const onEdit = (idTask) => {
      store
        .dispatch('task/queryById', idTask)
        .then((response) => {
          setSStorageObj('ParamData', response)
          router.push({ path: 'edit' })
        })
        .catch((error) => {
          console.log('根据任务id得到任务详情出现错误：', error)
          router.push({ path: 'list-page' })
        })
    }
    // 删除任务
    const onDelete = (idTask) => {
      ElMessageBox.confirm('确定要删除该任务吗？', '删除警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          store
            .dispatch('article/delById', idTask)
            .then(() => {
              toastSuccess('删除成功！')
              listPage()
            })
            .catch((error) => {
              console.log('删除任务时出现错误：', error)
            })
        })
        .catch(() => {})
    }
    // 点击标题，弹出对话框，显示任务相关内容
    const showTask = (idTask) => {
      store
        .dispatch('task/queryById', idTask)
        .then((response) => {
          flagDialogShow.value = true
          task.value = response
        })
        .catch((error) => {
          console.log('得到任务详情出现错误：', error)
        })
    }
    // 点击下载按钮
    const onDownload = (uuid) => {
      L('uuid：', uuid)
      if (!uuid || uuid === '') return
      store
        .dispatch('sys_ul_file/downloadEntity', uuid)
        .then((response) => {
          L('response：', response)
          resolveBlob(response)
        })
        .catch((error) => {
          L('error:', error)
        })
    }
    // 点击删除文件按钮
    const onDeleteFile = (uuid) => {
      ElMessageBox.confirm('确定要删除该文件吗？', '删除警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          store
            .dispatch('sys_ul_file/delByUuid', uuid)
            .then((response) => {
              if (response.data.statusCode === '20400') {
                toastSuccess(response.data.message)
              }
              listFile()
            })
            .catch((error) => {
              L('error:', error)
            })
        })
        .catch(() => {})
    }
    // 获取上传结果
    const getUploadResult = () => {
      listFile()
    }

    onMounted(() => {
      getIdAdmin()
      listCategory()
      listPage()
    })

    return {
      idAdmin,
      idCategory,
      tblDataList,
      tblFileList,
      treeSelectData,
      flagLoading,
      pageCurrent,
      pageSize,
      pageSizeArrray,
      recordCount,
      pageCount,
      flagDialogShow,
      flagDialogFile,
      task,
      idTask,

      getIdAdmin,
      formatDT,
      listCategory,
      listAllAdmin,
      listPage,
      listFile,
      onSizeChange,
      onCurrentChange,
      onEnabled,
      onFinished,
      onStatus,
      onAddSubTask,
      onDuty,
      onListFile,
      onDelete,
      onEdit,
      showTask,
      getUploadResult,
      onDownload,
      onDeleteFile,
    }
  },
})
</script>

<style lang="scss" scoped></style>
